# -*- coding: utf-8 -*-
"""
Module Description: 运行时日志工具
Date: 2018/1/17
Author:Bai Jin Ping
"""
import logging
import socket
from functools import wraps

# from log_output_py.logger_init import EventLogger, EventFormatter, SysLogHandler
from common import service_config


class GameNormalHandler(logging.StreamHandler):
    """游戏一般日志记录"""
    def __init__(self, *args, **kw):
        logging.StreamHandler.__init__(self, *args, **kw)
        self.setLevel(logging.DEBUG)
        formater = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
        self.setFormatter(formater)


# class RsyslogFormatter(EventFormatter):
#     """
#     A structured formatter for Rsyslog.
#     """
#     def __init__(self, fmt=None, rsyslog_tag="dq2"):
#         EventFormatter.__init__(self, fmt)
#         if fmt:
#             self.fmt_dict = fmt
#         else:
#             self.fmt_dict = {
#                 "file_name": "%(module)s",
#                 "log_level": "%(levelname)s",
#                 "line": "%(lineno)d",
#                 "host": socket.gethostname(),
#                 "traceid": "%(traceid)s",
#                 "server": "%(server)s",
#                 "action_id": "%(action_id)s",
#                 "appid": "%(appid)s",
#                 "message": "%(message)s",
#                 "@log_name": "%(name)s",
#                 "@fluentd_tag": rsyslog_tag,  # For syslog
#             }


def init_logger():
    """
    初始化日志Handler
    """
    _rtlogger.setLevel(logging.INFO)

    # 注册syslog日志logger
    # if service_config.RunLogMode.is_use_log_rsyslog():
    #     syslog_conf = service_config.config["remoteservices"]["rsyslog"]
    #     _rtlogger.propagate = False
    #     new_syslog_hdlr = SysLogHandler(mode=syslog_conf["log_mode"],
    #                                     host=syslog_conf["host"],
    #                                     port=syslog_conf["port"])
    #     new_syslog_hdlr.setFormatter(RsyslogFormatter(rsyslog_tag=syslog_conf["rsyslog_tag"]))
    #     new_syslog_hdlr.level = logging.WARNING
    #     _rtlogger.addHandler(new_syslog_hdlr)

    # 注册一般日志logger
    normal_handler = GameNormalHandler()
    _rtlogger.addHandler(normal_handler)


# if service_config.RunLogMode.is_use_log_rsyslog():
#     logging.setLoggerClass(EventLogger)

_rtlogger = logging.Logger('game.rt')


def add_extra_info(func):
    """增加额外信息(区服id、trace_id)"""
    @wraps(func)
    def wrapper(msg, *args, **kwargs):
        if "extra" not in kwargs.keys() or "server" not in kwargs.get("extra").keys():
            # 加入区服信息和追踪标识
            # 新增rid和接口参数
            from framework.firefly_dc.context import action_context_storage
            action_id = "unknown"
            rid = "unknown"
            trace_id = "empty"
            action_args = {}
            if action_context_storage.ctx is not None:
                action_id = action_context_storage.ctx.action_id
                trace_id = action_context_storage.ctx.trace_id
                rid = action_context_storage.ctx.rid
                # 防报错
                action_args = action_context_storage.ctx.request.args if action_context_storage.ctx.request else {}

            kwargs["extra"] = kwargs.get("extra") if kwargs.get("extra") else {}
            kwargs["extra"]["action_id"] = action_id
            kwargs["extra"]["traceid"] = trace_id
            if 'extra' not in kwargs["extra"]:
                # 使用内层extra，可以不必定义日志格式
                kwargs["extra"]["extra"] = {}

            kwargs["extra"]["extra"]["rid"] = rid
            # 接口参数采用拼接的方式，是因为能更清晰的查看，
            msg = str(msg)  # 增加强制装换，因为外部传入的不一定是字符串类型
            msg += "\n {}".format(str(action_args)) if action_args else ""

        func(msg, *args, **kwargs)
    return wrapper


@add_extra_info
def debug(msg, *args, **kwargs):
    _rtlogger.debug(msg, *args, **kwargs)


@add_extra_info
def info(msg, *args, **kwargs):
    _rtlogger.info(msg, *args, **kwargs)


@add_extra_info
def warning(msg, *args, **kwargs):
    _rtlogger.warning(msg, *args, **kwargs)


@add_extra_info
def error(msg, *args, **kwargs):
    _rtlogger.error(msg, *args, **kwargs)
